<?php

class Referer
{
	private static $instance = NULL;
	private $referer = null;
	private $updated = false;
	private $searcher = null;
	private $searched = null;

	function Referer($url = null)
	{
		if ($url != null)
			$this->referer = $url;
	}

	static function get()
	{
		if (self::$instance == NULL) {
			if (isset($_SERVER['HTTP_REFERER']))
				self::$instance = new Referer($_SERVER['HTTP_REFERER']);
			else
				self::$instance = new Referer();
		}

		return self::$instance;
	}

	function getReferer()
	{
		return $this->referer;
	}

	private function updateData()
	{
		if (!$this->updated) {
			$this->updated = true;
			$parts = parse_url($this->referer);
			if (isset($parts['query'])) {
				parse_str($parts['query'], $query);
				$search_engines = array(
					'anunciaros' => 'q',
					'aol' => 'q',
					'aolsearch' => 'q',
					'ask' => 'q',
					'bing' => 'q',
					'baidu' => 'wd',
					'excite' => 'q',
					'gigablast' => 'q',
					'google' => 'q',
					'lycos' => 'q',
					'webcrawler' => 'q',
					'yahoo' => 'p',
					'zoo' => 'q');

				preg_match('/(' . implode('|', array_keys($search_engines)) . ')\./', $parts['host'], $matches);
				if (isset($matches[1])) {
					$this->searcher = $matches[1];
					if (isset($query[$search_engines[$matches[1]]]) && (strlen($query[$search_engines[$matches[1]]]) > 0))
						$this->searched = $query[$search_engines[$matches[1]]];
				}
			}
		}
	}

	function getSearcher()
	{
		$this->updateData();
		return $this->searcher;
	}

	function getSearched()
	{
		$this->updateData();
		return $this->searched;
	}
}
?>